package com.qfedu.edu.seckill.orderservice.slot.impl;

import com.qfedu.edu.seckill.constance.RedisConstance;
import com.qfedu.edu.seckill.exception.BusinessException;
import com.qfedu.edu.seckill.manager.RedisManager;
import com.qfedu.edu.seckill.orderservice.slot.generic.GenericSlot;
import com.qfedu.edu.seckill.result.R;
import com.qfedu.edu.seckill.result.ResponseCode;
import com.qfedu.edu.seckill.utils.HttpResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaobobo
 * @title: StockNumCheckSlot
 * @projectName cd-java-2404-seckill-parent
 * @description: TODO
 * @date 2025/2/6  9:49
 */
@Component
@Slf4j
public class StockNumCheckSlot extends GenericSlot {

    @Autowired
    private RedisManager redisManager;

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 3;
    }

    @Override
    public void dealRequest(HttpServletRequest request, HttpServletResponse response) {

        log.info("StockNumCheckInterceptor执行了....");
        String classId = request.getParameter("classId");
        /**
         * 逻辑：
         *    先找到当前商品在Redis中的库存的数量...
         *    找到当前商品放行的购买人数
         *    比较放行的人数 是不是 小于等于这个库存数量...
         */
        //首先构建这个库存的key
        String stockKey = RedisConstance.getProStockPrefix() + classId;
        //找到库存信息
        Integer stockNum = (Integer) redisManager.getObject(stockKey);
        if (null == stockNum) {
            //说明没有库存数据
            throw new BusinessException(ResponseCode.STOCK_NUM_EXCEPTION);
        }
        //执行到这里有库存信息 那么接下来拿到这个计数的信息
        //构建计数的这个key
        //首先构建这个key
        String countKey = RedisConstance.getCountSellPrefix() + classId;
        //从Redis中拿到这个计数的信息
        Object object = redisManager.getObject(countKey);
        if (null == object) {
            //说明：第一次这个商品被秒杀
            log.info("第一次这个商品被秒杀");
            return;
        }
        //执行到这里 说明有数据
        Integer count = (Integer) object;
        if (count >= stockNum) {
            //说明商品已经秒杀完
            log.info("商品已经秒杀完....");
            throw new BusinessException(ResponseCode.PRO_COUNT_OVER_EXCEPTION);
        }
        //如果执行到这里 说明还有商品...
        log.info("库存充足可以秒杀....");
    }
}
